-- DEPOIS QUE GERAR A OF DESMEMBRADA GERA TAMBEM AS TABELAS EXTENDIDAS 
CREATE OR REPLACE TRIGGER T_ATS_DETOF_AFTER 
AFTER INSERT ON ATS_DETOF FOR EACH ROW
DECLARE
v_ofcons NUMBER;
v_etiqueta NUMBER;
BEGIN
  IF INSERTING THEN
  
    FOR I IN 
    (
      SELECT * FROM F_OF, F_VERCOMP
      WHERE COF_CODIOF = :NEW.DOF_CODIOF
      AND   COF_CODINP = VCP_CODCNP
     ) LOOP
       
       SELECT SEQ_ATS_OFCONS.NEXTVAL INTO v_ofcons FROM DUAL;
       
       INSERT INTO ATS_OFCONS
       ( OFC_CODIGO,OFC_COFDET, OFC_CODPRO, OFC_CODSEQ, OFC_OFCATI, OFC_LOCEST, OFC_QTCOMP, 
         OFC_QTDEMP, OFC_QTREAL, OFC_QTSUCA,OFC_LCPROC, OFC_PPERDA, OFC_ABTPRO, OFC_RASTRE, 
         OFC_IMPOF, OFC_PVARIA, OFC_QTDITE )
       VALUES( v_ofcons, :NEW.DOF_CODIGO,I.COF_CODPRO, I.VCP_CODSEQ, I.COF_OFCATI, I.VCP_LCPROC, I.VCP_QTPROD * :NEW.DOF_QTDPRG, 
          0, 0,0, I.VCP_LCPROC, I.VCP_PPERDA, I.VCP_ABTPRO, I.VCP_RASTRE, 
          I.VCP_IMPOF, I.VCP_PVARIA, I.VCP_QTPROD); 
       
       INSERT INTO ATS_DETOFCONS
       (DFC_COFCON, DFC_CDCOMP, DFC_QTDITE, DFC_QTDEMP, DFC_QTDCON, DFC_QTDSUC, DFC_LOCEST)
       VALUES(v_ofcons,I.VCP_CDCOMP,I.VCP_QTPROD,0,0,0,I.VCP_LCPROC);
       
       
       FOR X IN 
       ( 
         SELECT * FROM F_SIMILAR
         WHERE PSM_CODCNP = I.COF_CODINP
         AND   PSM_ROTEIR = I.COF_ROTEIR
         AND   PSM_CODSEQ = I.VCP_CODSEQ
         AND   PSM_PRORIG = I.VCP_CDCOMP
       ) LOOP
         
         INSERT INTO ATS_DETOFCONS
         (DFC_COFCON, DFC_CDCOMP, DFC_QTDITE, DFC_QTDEMP, DFC_QTDCON, DFC_QTDSUC, DFC_LOCEST)
         VALUES(v_ofcons,X.PSM_PROSIM, X.PSM_QTDE,0,0,0,I.VCP_LCPROC);
       END LOOP;
    END LOOP;           
     
  END IF;           
END;